<template>
  <div class="coupon-container">
    <div class="coupon-container_body">
      <div class="coupon-tabs">
        <span
          :class="['tab', currentCoupon === item.value && 'active-tab']"
          v-for="item in couponTypeList"
          :key="item.value"
          @click.stop="handleChangeCurrentCoupon(item.value)"
        >
          {{ item.label }}
          <em class="tab_badge" v-if="item.value == 'mine' && couponExpiresSoon">即将过期</em>
        </span>
      </div>
      <div :class="['coupon-list', isEmpty && 'empty-list']">
        <div
          :class="{
            'flex-center': true,
            'coupon-item': true,
            'invalid-item': currentCoupon === 'invalid' || item.expireSecond === 0
          }"
          v-for="item in couponList"
          :key="item"
        >
          <div class="money-part">
            <div class="money">
              {{ moneySymbol }}<strong>{{ item.amount_text }}</strong>
            </div>
            <p class="tip">现金券</p>
          </div>
          <div class="detail-part" :class="{'has-time':item.expireSecond}">
            <div class="coupon-time" v-if="item.expireSecond">
              <time-to :second="item.expireSecond" />
            </div>
            <div class="flex-center">
              <div class="desc-box">
                <h3 class="title">
                  <span :title="item.name">{{ item.name }}</span>
                </h3>
                <p class="mr10 mb10" v-if="item.draw_status !== 'nd'">有效期至{{ getFormatTime(item.expire_at) }}</p>
                <div>
                  <p class="intro" :title="item.instruct">使用说明<el-icon class="right-arrow-icon">
                    <ArrowRight /> </el-icon>
                  </p>
                </div>
              </div>
              <el-button
                v-if="item.draw_status === 'nd' && item.expireSecond !== 0"
                class="obtain-btn"
                type="danger"
                size="small"
                round
                @click.stop="handleObtainCoupon(item.id)"
                >立即领取</el-button>
              <el-button
                v-if="
                  item.status === 0 &&
                  currentCoupon === 'mine' &&
                  item.expireSecond !== 0
                "
                class="obtain-btn"
                type="danger"
                size="small"
                round
                @click.stop="toPayCenter"
                >立即使用</el-button>
            </div>
            <div class="invalid-icon">
              <span>已失效</span>
            </div>
          </div>
        </div>
        <div class="empty-status" v-if="isEmpty">
          <div class="empty-desc">
            <svg-icon iconClass="coupon-empty-icon" :size="48" />
            <div>
              <span v-show="currentCoupon === 'limitObtain'">
                当前无可领取的券，您可查看<em
                  class="pointer"
                  @click="handleChangeCurrentCoupon('mine')"
                  >【已领优惠券】</em>
              </span>
              <span v-show="currentCoupon === 'mine'">
                暂无优惠券，您可前往<em>【限时领取】领券</em>
              </span>
              <span v-show="currentCoupon === 'invalid'">暂无失效券</span>
              <p>加入官方用户群参与不定期抽奖活动!</p>
            </div>
          </div>
          <div class="empty-wx-code">
            <img :src="imgSrc" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ArrowRight } from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import { systemAppStore } from "@/stores/system";
import { userAppStore } from "@/stores/user";
import { getLimitObtainCoupons, obtainCoupon } from "@/api/coupon";
import { parseTime, getQueryObject } from "@/utils";
import { getLeftTime, formatMoney, getWeChatImg } from "@/utils/costum";
import { createVNode } from "vue";
import { invokeAPi } from "@/xz-fn";
import TimeTo from "@/components/time-to.vue";
import PsMessage from "@/components/message/index";
import eventBus from '@/utils/mitt';
const router = useRouter()
const _systemAppStore_ = systemAppStore();
const _userAppStore_ = userAppStore();
const { appInfo } = storeToRefs(_systemAppStore_);
const { couponNumber, couponExpiresSoon } = storeToRefs(_userAppStore_);
const couponList = ref<any>([]);
const couponTypeList = ref([
  {
    label: "限时领取",
    value: "limitObtain"
  },
  {
    label: "已领优惠券",
    value: "mine"
  },
  {
    label: "已失效优惠券",
    value: "invalid"
  }
]);
const currentCoupon = ref("limitObtain");
const imgSrc = ref(getWeChatImg());
const moneySymbol = computed(() => "￥");
const isEmpty = computed(() => !couponList.value?.length);
let timer: number | null = null;
const getFormatTime = computed(() => {
  return (time: any) => {
    return parseTime(time, "{y}/{m}/{d} {h}:{i}");
  };
});

onMounted(() => {
  getCoupons();
  _userAppStore_.setCanReceiveMaxDiscount(0);
});
onUnmounted(() => {
  timer && clearTimeout(timer);
});

function handleChangeCurrentCoupon(coupon: string) {
  if (currentCoupon.value === coupon) {
    return;
  }
  currentCoupon.value = coupon;
  couponList.value = [];
  if (coupon === "limitObtain") {
    getCoupons();
  } else {
    getMyCoupons(coupon === "mine");
  }
};
// 获取优惠券列表数据
function getCoupons() {
  timer && clearTimeout(timer);
  getLimitObtainCoupons({
    pkg_id: appInfo.value.allPackages[0],
    show_pos: "draw_center",
    sort: "amount_desc",
    hide_has_draw: true,
    max_size: 200,
    draw_method: "hand"
  })
    .then(({ data, res_headers }: any) => {
      let { date: serverTime } = res_headers || {};
      const localTime = Math.round(Date.now() / 1000);
      serverTime = serverTime
        ? Math.round(new Date(serverTime).getTime() / 1000)
        : localTime;
      couponList.value = (data.list?.length ? data.list : []).map(
        (it: any) => {
          const { stop_time } = it;
          if (stop_time) {
            const expire_at = new Date(stop_time).getTime() / 1000;
            it.serverTime = serverTime;
            it.localTime = localTime;
            it.expire_at = expire_at;
            it.expireSecond = getLeftTime(expire_at, serverTime, localTime);
          }
          it.amount_text = formatMoney(it.amount);
          return it;
        }
      );
      startDownTime();
    });
};
// 获取我的券
function getMyCoupons(isNow = true) {
  _userAppStore_.getMyCoupons(isNow)
    .then((data: any) => {
      couponList.value = data.map((it: any) => {
        if (isNow) {
          const { expire_at, serverTime, localTime } = it;
          it.expireSecond = getLeftTime(expire_at, serverTime, localTime);
        }
        it.amount_text = formatMoney(it.amount);
        return it;
      });
      startDownTime();
    });
};
// 领取优惠券
function handleObtainCoupon(coupon_id: number) {
  timer && clearTimeout(timer);
  obtainCoupon({ coupon_id })
    .then(() => {
      const messageNode = createMessageNode();
      PsMessage({
        message: messageNode,
        customClass: "right-center-pos"
      });
      couponList.value = couponList.value.filter(
        (coupon: { id: number }) => coupon_id !== coupon.id
      );
      // _userAppStore_.getMyCoupons();

      // eventBus.emit("updateUserCoupon"); 由fq_NotifyWebMessageEx代替
      invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({action: "user-coupon-change"}))
    });
};
function createMessageNode() {
  const h = createVNode;
  const vnode = h("div", { class: "bar" }, [
    h("span", {}, `领取成功,`),
    h(
      "span",
      {
        class: "coupon-center-message",
        onClick: () => {
          toPayCenter();
        }
      },
      "立即使用"
    )
  ]);
  return vnode;
}
function toPayCenter() {
  router.push({ name: "UserCenter" });
  PsMessage.closeAll();
}
function startDownTime() {
  timer && clearTimeout(timer);
  if (!couponList.value.filter((it: any) => it.expireSecond).length) {
    return;
  }
  timer = setTimeout(() => {
    couponList.value.forEach((it: any) => {
      if (it.expireSecond) {
        const { expire_at, serverTime, localTime } = it;
        it.expireSecond = getLeftTime(expire_at, serverTime, localTime);
      }
    });
    timer = null;
    startDownTime();
  }, 1000) as unknown as number;
}
</script>
<style lang="scss">
.coupon-center-message {
  margin-left: 4px;
  color: #ff2c2c;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
</style>
<style lang="scss" scoped>
.coupon-container {
  width: 100%;
  padding: 5px;
  overflow: hidden;
  .coupon-container_body{
    padding: 25px 20px 25px 25px;
    height: 100%;
    overflow: scroll;
  }
}
.coupon-tabs {
  height: 56px;
  margin-bottom: 20px;
  padding: 0 40px;
  line-height: 56px;
  background: rgba(51,51,51,0.05);
  border-radius: 10px;

  .tab {
    margin-right: 24px;
    color: var(--el-text-color-primary);
    font-size: 14px;
    cursor: pointer;
    transition: all 0.25s ease-in-out;
    position: relative;
    &.active-tab {
      font-weight: bold;
      color: var(--el-color-primary);
    }
    .tab_badge {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translate(-50%, -100%);
      height: 22px;
      line-height: 22px;
      padding: 0 10px;
      background: linear-gradient(180deg, #ff7272 0%, #ff2c2c 100%);
      font-weight: 400;
      font-size: 12px;
      color: #ffffff;
      white-space: nowrap;
      border-radius: 22px;
      -webkit-text-fill-color: currentColor;
      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translate(-50%, 100%);
        border: 4px solid transparent;
        border-top-color: #ff2c2c;
      }
    }
    &:hover {
      color: var(--el-color-primary);
    }
  }
}
.coupon-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-row-gap: 20px;
  grid-column-gap: 20px;

  &.empty-list {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    margin-top: 100px;
  }
}
.coupon-item {
  position: relative;
  background-color: #ffeeee;
  border-radius: 8px;
  overflow: hidden;
  flex: none;
  height: 126px;

  .invalid-icon {
    display: none;
  }
}
.invalid-item {
  position: relative;
  opacity: 0.5;
  .invalid-icon {
    display: block;
    position: absolute;
    right: 0;
    top: 0;
    width: 82px;
    height: 78px;
    background-image: url(@/assets/images/invalid.png);
    background-size: cover;
    font-size: 14px;
    color: #fff;
    span {
      display: flex;
      width: 100%;
      height: 100%;
      justify-content: center;
      align-items: center;
      transform: rotate(45deg) translateY(-16px);
      white-space: nowrap;
      font-size: 10px;
    }
  }
  .desc-box{
    .title{
      margin-right: 40px;
    }
  }
}

.money-part {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 118px;
  height: 100%;
  color: #f84d4d;
  border-right: 1px dashed #f84d4d;
  font-size: 12px;
  line-height: 14px;
  &::before,
  &::after {
    position: absolute;
    left: calc(100% - 7px);
    display: block;
    content: "";
    width: 14px;
    height: 15px;
    background-color: #fff;
    border-radius: 50%;
  }
  &::before {
    top: -7px;
  }
  &::after {
    bottom: -7px;
  }
  .money {
    margin-bottom: 6px;
    font-size: 16px;
    line-height: 20px;
    strong {
      font-size: 32px;
      line-height: 38px;
    }
  }
}
.detail-part {
  flex: 1;
  padding: 0 10px 0 27px;
  overflow: hidden;
  &.has-time{
    align-self: flex-start;
    padding-top: 10px;
  }
}
.coupon-time {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 7px;
}
.desc-box {
  flex: 1;
  font-size: 12px;
  color: var(--el-text-color-regular);
  overflow: hidden;
  .title {
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    color: var(--el-text-color-primary);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .right-arrow-icon {
    position: relative;
    top: 1px;
  }
  .intro {
    flex-shrink: 0;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
  }
}
.obtain-btn {
  margin-right: 6px;
  --el-button-bg-color: #f84d4d;
  --el-button-hover-bg-color: #eb4040;
  --el-button-size: 32px;
  min-width: 76px;
}

.empty-status {
  display: flex;
  flex-flow: column nowrap;
  align-items: center;

  .empty-desc {
    display: flex;
    align-items: center;
    font-weight: 400;
    font-size: 12px;
    color: var(--el-text-color-primary);
    line-height: 20px;

    .svg-icon {
      margin-right: 10px;
    }
  }

  .empty-wx-code {
    width: 160px;
    height: 160px;
    margin-top: 20px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
